<template>
  <!-- Instructions Stage -->
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-slate-200 shadow-lg">
        <CardHeader class="text-center pb-8">
          <div
            class="w-16 h-16 bg-gradient-to-br from-slate-500 to-gray-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
            <ArrowRight class="w-8 h-8 text-white"/>
          </div>
          <CardTitle class="text-2xl text-slate-800">{{ $t('sequenceReasoningTest.title') }}</CardTitle>
          <p class="text-slate-600 mt-2">{{ $t('sequenceReasoningTest.description') }}</p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="bg-gradient-to-r from-slate-50 to-gray-50 rounded-xl p-6 border border-slate-200">
            <h3 class="font-semibold text-slate-900 mb-4 flex items-center gap-2">
              <Star class="w-5 h-5"/>
              {{ $t('sequenceReasoningTest.instructions.title') }}
            </h3>
            <div class="space-y-3 text-slate-700">
              <div class="flex gap-3"><span class="step-number">1</span>
                <p>{{ $t('sequenceReasoningTest.instructions.step1') }}</p></div>
              <div class="flex gap-3"><span class="step-number">2</span>
                <p>{{ $t('sequenceReasoningTest.instructions.step2') }}</p></div>
              <div class="flex gap-3"><span class="step-number">3</span>
                <p>{{ $t('sequenceReasoningTest.instructions.step3') }}</p></div>
              <div class="flex gap-3"><span class="step-number">4</span>
                <p>{{ $t('sequenceReasoningTest.instructions.step4') }}</p></div>
            </div>
          </div>
          <div class="grid md:grid-cols-3 gap-4">
            <div class="info-box">
              <div class="info-box-title text-slate-600">{{ ALL_QUESTIONS.length }}</div>
              <div class="info-box-body">{{ $t('sequenceReasoningTest.summary.questions') }}</div>
            </div>
            <div class="info-box">
              <div class="info-box-title text-gray-600">8</div>
              <div class="info-box-body">{{ $t('sequenceReasoningTest.summary.timeLimit') }}</div>
            </div>
            <div class="info-box">
              <div class="info-box-title text-slate-600">3</div>
              <div class="info-box-body">{{ $t('sequenceReasoningTest.summary.types') }}</div>
            </div>
          </div>
          <Button class="w-full bg-gradient-to-r from-slate-500 to-gray-600 hover:from-slate-600 hover:to-gray-700 text-white py-3 text-lg font-semibold shadow-lg"
                  size="lg"
                  @click="handleStartTest">
            {{ $t('sequenceReasoningTest.startTest') }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Test Stage -->
  <div v-else-if="stage === 'test'" class="max-w-4xl mx-auto space-y-6">
    <transition name="slide-down">
      <div v-if="showFeedback" class="fixed top-20 left-1/2 transform -translate-x-1/2 z-50">
        <Card :class="['border-0 shadow-lg', feedbackCorrect ? 'bg-green-500 text-white' : 'bg-red-500 text-white']">
          <CardContent class="py-3 px-6">
            <div class="flex items-center gap-2">
              <CheckCircle v-if="feedbackCorrect" class="w-5 h-5"/>
              <XCircle v-else class="w-5 h-5"/>
              <span class="font-semibold">{{ feedbackCorrect ? $t('sequenceReasoningTest.feedback.correct') : $t('sequenceReasoningTest.feedback.incorrect') }}</span>
              <span class="text-sm">({{ question.rule }})</span>
            </div>
          </CardContent>
        </Card>
      </div>
    </transition>

    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4 flex-wrap">
        <Badge class="bg-slate-100 text-slate-700 border-slate-300" variant="outline">{{ $t('sequenceReasoningTest.test.progress', { current: currentQuestion + 1, total: ALL_QUESTIONS.length }) }}
        </Badge>
        <Badge :class="typeClass" variant="outline">{{ typeName }}</Badge>
      </div>
      <div class="flex items-center gap-2">
        <Clock class="w-4 h-4 text-slate-500"/>
        <span :class="['font-mono text-lg font-bold', timeLeft <= 60 ? 'text-red-500' : 'text-slate-700']">
          {{ Math.floor(timeLeft / 60) }}:{{ (timeLeft % 60).toString().padStart(2, '0') }}
        </span>
      </div>
    </div>

    <Progress :model-value="(currentQuestion / ALL_QUESTIONS.length) * 100" class="h-2"/>

    <Card class="bg-white/90 backdrop-blur-sm border-slate-200 shadow-lg">
      <CardContent class="p-8">
        <div class="text-center mb-8">
          <h2 class="text-xl font-semibold text-slate-800 mb-6">{{ $t('sequenceReasoningTest.test.findNext') }}</h2>
          <div class="flex items-center justify-center gap-4 mb-8">
            <template v-for="(item, index) in question.sequence" :key="index">
              <div :class="[
                'min-w-16 h-16 rounded-xl border-2 border-dashed border-slate-300 flex items-center justify-center',
                item === '?' ? 'bg-gradient-to-br from-slate-100 to-slate-200' : 'bg-white',
                question.type === 'shape' ? 'text-3xl' : 'text-xl font-bold text-slate-800'
              ]">
                <span v-if="item === '?'" class="text-2xl text-slate-400">?</span>
                <span v-else>{{ item }}</span>
              </div>
              <ArrowRight v-if="index < question.sequence.length - 1" class="w-4 h-4 text-slate-400"/>
            </template>
          </div>
        </div>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 max-w-2xl mx-auto">
          <Button v-for="(option, index) in question.options" :key="index"
                  :class="['w-full h-16 text-lg', { 'bg-gradient-to-br from-slate-500 to-gray-600 text-white': selectedAnswer === option }, question.type === 'shape' ? 'text-2xl' : 'font-bold']" :variant="selectedAnswer === option ? 'default' : 'outline'"
                  @click="handleAnswerSelect(option)">
            {{ option }}
          </Button>
        </div>
        <div class="flex justify-center mt-8">
          <Button :disabled="selectedAnswer === null" class="bg-gradient-to-r from-slate-500 to-gray-600 hover:from-slate-600 hover:to-gray-700 text-white px-8 py-2 font-semibold"
                  @click="handleSubmitAnswer">
            {{ $t('sequenceReasoningTest.test.submit') }}
          </Button>
        </div>
      </CardContent>
    </Card>
  </div>

  <!-- Results Stage -->
  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-slate-200 shadow-xl">
        <CardHeader class="text-center pb-6">
          <div
            class="w-20 h-20 bg-gradient-to-br from-slate-500 to-gray-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
            <Trophy class="w-10 h-10 text-white"/>
          </div>
          <CardTitle class="text-3xl text-slate-800 mb-2">{{ $t('sequenceReasoningTest.results.title') }}</CardTitle>
          <div class="text-6xl font-bold bg-gradient-to-r from-slate-500 to-gray-600 bg-clip-text text-transparent">
            {{ results.finalScore }}
          </div>
          <p class="text-slate-600">{{ $t('sequenceReasoningTest.results.scoreTitle') }}</p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="grid grid-cols-2 gap-4">
            <div class="info-box">
              <div class="info-box-title text-slate-600">{{ results.correctAnswers }}/{{ ALL_QUESTIONS.length }}</div>
              <div class="info-box-body">{{ $t('sequenceReasoningTest.results.correctCount') }}</div>
            </div>
            <div class="info-box">
              <div class="info-box-title text-gray-600">{{ results.accuracy }}%</div>
              <div class="info-box-body">{{ $t('sequenceReasoningTest.results.accuracy') }}</div>
            </div>
          </div>
          <div class="space-y-3">
            <div class="result-row"><span class="text-slate-600">{{ $t('sequenceReasoningTest.test.types.number') }}</span><span
              class="font-semibold text-slate-800">{{ results.numberCorrect }}/5</span></div>
            <div class="result-row"><span class="text-slate-600">{{ $t('sequenceReasoningTest.test.types.shape') }}</span><span
              class="font-semibold text-slate-800">{{ results.shapeCorrect }}/3</span></div>
            <div class="result-row"><span class="text-slate-600">{{ $t('sequenceReasoningTest.test.types.pattern') }}</span><span
              class="font-semibold text-slate-800">{{ results.patternCorrect }}/2</span></div>
          </div>
          <Button class="w-full bg-gradient-to-r from-slate-500 to-gray-600 hover:from-slate-600 hover:to-gray-700 text-white py-3 text-lg font-semibold shadow-lg"
                  size="lg"
                  @click="handleComplete">
            {{ $t('sequenceReasoningTest.results.viewDetails') }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>
</template>

<script setup>
import {ref, computed, watch, onUnmounted} from 'vue';
import { useI18n } from 'vue-i18n';
import {ArrowRight, Clock, Trophy, Star, CheckCircle, XCircle} from 'lucide-vue-next';

const { t } = useI18n();
const emit = defineEmits(['complete']);

// --- Constants ---
const ALL_QUESTIONS = computed(() => [
  {
    id: 1,
    type: 'number',
    sequence: [2, 4, 6, 8, '?'],
    options: [10, 12, 14, 16],
    correct: 10,
    rule: t('sequenceReasoningTest.rules.even')
  }, {
    id: 2,
    type: 'number',
    sequence: [1, 4, 9, 16, '?'],
    options: [20, 25, 30, 35],
    correct: 25,
    rule: t('sequenceReasoningTest.rules.square')
  }, {
    id: 3,
    type: 'number',
    sequence: [3, 6, 12, 24, '?'],
    options: [36, 42, 48, 54],
    correct: 48,
    rule: t('sequenceReasoningTest.rules.multiply2')
  }, {
    id: 4,
    type: 'number',
    sequence: [1, 1, 2, 3, 5, '?'],
    options: [7, 8, 9, 10],
    correct: 8,
    rule: t('sequenceReasoningTest.rules.fibonacci')
  }, {
    id: 5,
    type: 'number',
    sequence: [2, 6, 18, 54, '?'],
    options: [108, 162, 180, 216],
    correct: 162,
    rule: t('sequenceReasoningTest.rules.multiply3')
  }, {
    id: 6,
    type: 'shape',
    sequence: ['○', '●', '○', '●', '?'],
    options: ['○', '●', '◇', '◆'],
    correct: '○',
    rule: t('sequenceReasoningTest.rules.alternating')
  }, {
    id: 7,
    type: 'shape',
    sequence: ['△', '□', '○', '△', '?'],
    options: ['□', '○', '△', '◇'],
    correct: '□',
    rule: t('sequenceReasoningTest.rules.repeating')
  }, {
    id: 8,
    type: 'shape',
    sequence: ['●', '●●', '●●●', '●●●●', '?'],
    options: ['●●●●●', '●●●', '●', '●●'],
    correct: '●●●●●',
    rule: t('sequenceReasoningTest.rules.incrementing')
  }, {
    id: 9,
    type: 'pattern',
    sequence: ['AB', 'BC', 'CD', 'DE', '?'],
    options: ['EF', 'FG', 'EA', 'DF'],
    correct: 'EF',
    rule: t('sequenceReasoningTest.rules.consecutiveLetters')
  }, {
    id: 10,
    type: 'pattern',
    sequence: ['A1', 'B2', 'C3', 'D4', '?'],
    options: ['E5', 'F6', 'A5', 'D5'],
    correct: 'E5',
    rule: t('sequenceReasoningTest.rules.letterNumberIncrement')
  }
]);

// --- State ---
const stage = ref('instructions');
const currentQuestion = ref(0);
const selectedAnswer = ref(null);
const answers = ref(new Array(ALL_QUESTIONS.value.length).fill(null));
const timeLeft = ref(480);
const startTime = ref(0);
const showFeedback = ref(false);
const feedbackCorrect = ref(false);

let timer = null;

// --- Computed Properties ---
const question = computed(() => ALL_QUESTIONS.value[currentQuestion.value]);
const typeName = computed(() => t(`sequenceReasoningTest.test.types.${question.value.type}`));
const typeClass = computed(() => {
  switch (question.value.type) {
    case 'number':
      return 'bg-blue-100 text-blue-700 border-blue-300';
    case 'shape':
      return 'bg-green-100 text-green-700 border-green-300';
    case 'pattern':
      return 'bg-purple-100 text-purple-700 border-purple-300';
    default:
      return '';
  }
});
const results = computed(() => {
  if (stage.value !== 'results') return {};
  const correctAnswers = answers.value.filter((answer, index) => answer === ALL_QUESTIONS.value[index].correct).length;
  const accuracy = Math.round((correctAnswers / ALL_QUESTIONS.value.length) * 100);
  const numberCorrect = answers.value.slice(0, 5).filter((a, i) => a === ALL_QUESTIONS.value[i].correct).length;
  const shapeCorrect = answers.value.slice(5, 8).filter((a, i) => a === ALL_QUESTIONS.value[i + 5].correct).length;
  const patternCorrect = answers.value.slice(8).filter((a, i) => a === ALL_QUESTIONS.value[i + 8].correct).length;
  return {finalScore: accuracy, correctAnswers, accuracy, numberCorrect, shapeCorrect, patternCorrect};
});

// --- Methods ---
const handleStartTest = () => {
  stage.value = 'test';
  startTime.value = Date.now();
};

const handleAnswerSelect = (answer) => {
  selectedAnswer.value = answer;
};

const handleSubmitAnswer = () => {
  if (selectedAnswer.value === null) return;
  const newAnswers = [...answers.value];
  newAnswers[currentQuestion.value] = selectedAnswer.value;
  answers.value = newAnswers;

  const isCorrect = selectedAnswer.value === question.value.correct;
  feedbackCorrect.value = isCorrect;
  showFeedback.value = true;

  setTimeout(() => {
    showFeedback.value = false;
    selectedAnswer.value = null;
    if (currentQuestion.value < ALL_QUESTIONS.value.length - 1) {
      currentQuestion.value++;
    } else {
      stage.value = 'results';
    }
  }, 1500);
};

const handleComplete = () => {
  emit('complete', {
    id: Date.now().toString(),
    testType: 'sequence-reasoning',
    score: results.value.finalScore,
    completedAt: new Date(),
    duration: Math.round((Date.now() - startTime.value) / 1000),
    details: {
      totalQuestions: ALL_QUESTIONS.value.length,
      correctAnswers: results.value.correctAnswers,
      accuracy: results.value.accuracy,
      numberCorrect: results.value.numberCorrect,
      shapeCorrect: results.value.shapeCorrect,
      patternCorrect: results.value.patternCorrect,
    }
  });
};

// --- Lifecycle Hooks ---
watch(stage, (newStage) => {
  if (newStage === 'test' && !timer) {
    timer = setInterval(() => {
      if (timeLeft.value <= 1) {
        stage.value = 'results';
        clearInterval(timer);
      } else {
        timeLeft.value--;
      }
    }, 1000);
  } else if (newStage !== 'test' && timer) {
    clearInterval(timer);
    timer = null;
  }
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
});

</script>

<style scoped>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.slide-down-enter-active, .slide-down-leave-active {
  transition: all 0.3s ease-out;
}

.slide-down-enter-from, .slide-down-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}

.step-number {
  @apply w-6 h-6 bg-slate-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5;
}

.info-box {
  @apply text-center p-4 bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl border border-slate-200;
}

.info-box-title {
  @apply text-2xl font-bold text-slate-600 mb-1;
}

.info-box-body {
  @apply text-sm text-slate-700;
}

.result-row {
  @apply flex justify-between items-center p-3 bg-slate-50 rounded-lg;
}
</style>
